<template>
  <div class="resource-manage-page">
    <div class="page-header">
      <h2>资源管理</h2>
      <p>审核和管理平台上的所有资源</p>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <el-row :gutter="20" align="middle">
        <el-col :span="3">
          <el-select v-model="filterCategory" placeholder="选择分类" style="width: 100%" @change="handleSearch">
            <el-option label="全部分类" value="" />
            <el-option label="教学课件" value="TEACHING" />
            <el-option label="科研资料" value="SCIENTIFIC" />
            <el-option label="图书文献" value="LITERATURE" />
            <el-option label="共享设备" value="EQUIPMENT" />
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-select v-model="filterStatus" placeholder="选择状态" style="width: 100%" @change="handleSearch">
            <el-option label="全部状态" value="" />
            <el-option label="待审核" value="PENDING" />
            <el-option label="已通过" value="APPROVED" />
            <el-option label="已拒绝" value="REJECTED" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索资源标题、描述或上传者"
            prefix-icon="Search"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
        </el-col>
        <el-col :span="10" style="text-align: right;">
          <el-button type="warning" @click="showPendingResources">
            <el-icon><Clock /></el-icon>
            待审核资源
          </el-button>
        <el-button type="primary" @click="openBookingManageDialog">
          <el-icon><Calendar /></el-icon>
          设备预约
        </el-button>
        </el-col>
      </el-row>
      
      <!-- 筛选状态提示 -->
      <div class="filter-status" v-if="hasActiveFilters">
        <el-tag type="info" size="small">
          <el-icon><Search /></el-icon>
          当前筛选：
          <span v-if="filterCategory">{{ getCategoryName(filterCategory) }}</span>
          <span v-if="filterStatus">{{ getStatusName(filterStatus) }}</span>
          <span v-if="searchKeyword">关键词："{{ searchKeyword }}"</span>
          <el-button 
            type="text" 
            size="small" 
            @click="clearFilters"
            style="margin-left: 8px; color: #409EFF;"
          >
            清除筛选
          </el-button>
        </el-tag>
      </div>
    </div>

    <!-- 资源列表 -->
    <div class="resource-table">
      <el-table :data="resourceList" v-loading="loading" style="width: 100%">
        <!-- 添加隐藏的ID列用于调试 -->
        <el-table-column prop="id" label="ID" width="80" v-if="false" />
        <el-table-column prop="resourceId" label="资源编号" width="120" />
        <el-table-column prop="title" label="资源标题" min-width="200" />
        <el-table-column prop="category" label="分类" width="120">
          <template #default="scope">
            <el-tag :type="getCategoryTagType(scope.row.category)">
              {{ getCategoryName(scope.row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.type)">
              {{ getTypeName(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="uploaderName" label="上传者" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="viewCount" label="浏览次数" width="100" />
        <el-table-column prop="downloadCount" label="下载次数" width="100" />
        <el-table-column prop="createTime" label="上传时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewResourceDetail(scope.row)">
              查看
            </el-button>
            <el-button 
              v-if="scope.row.status === 'APPROVED'"
              type="warning" 
              size="small" 
              @click="editResource(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              v-if="scope.row.status === 'PENDING'"
              type="success" 
              size="small" 
              @click="reviewResource(scope.row, 'APPROVED')"
            >
              通过
            </el-button>
            <el-button 
              v-if="scope.row.status === 'PENDING'"
              type="danger" 
              size="small" 
              @click="reviewResource(scope.row, 'REJECTED')"
            >
              拒绝
            </el-button>
            <el-button 
              v-if="scope.row.status !== 'PENDING'"
              type="warning" 
              size="small" 
              @click="deleteResource(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 资源详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="资源详情"
      width="70%"
      :before-close="handleCloseDetail"
    >
      <div v-if="currentResource" class="resource-detail">
        <div class="detail-header">
          <h3>{{ currentResource.title }}</h3>
          <div class="detail-meta">
            <el-tag :type="getCategoryTagType(currentResource.category)">
              {{ getCategoryName(currentResource.category) }}
            </el-tag>
            <el-tag :type="getTypeTagType(currentResource.type)" style="margin-left: 8px;">
              {{ getTypeName(currentResource.type) }}
            </el-tag>
            <el-tag :type="getStatusTagType(currentResource.status)" style="margin-left: 8px;">
              {{ getStatusName(currentResource.status) }}
            </el-tag>
          </div>
        </div>
        
        <div class="detail-content">
          <p><strong>描述：</strong>{{ currentResource.description }}</p>
          
          <div v-if="currentResource.type === 'DOCUMENT'" class="file-detail">
            <p><strong>文件名：</strong>{{ currentResource.fileName }}</p>
            <p><strong>文件大小：</strong>{{ formatFileSize(currentResource.fileSize) }}</p>
            <p><strong>文件类型：</strong>{{ currentResource.fileExtension?.toUpperCase() }}</p>
          </div>
          
          <div v-if="currentResource.type === 'EQUIPMENT'" class="equipment-detail">
            <p><strong>设备信息：</strong></p>
            <pre>{{ currentResource.equipmentInfo }}</pre>
          </div>
          
          <div class="detail-info">
            <p><strong>上传者：</strong>{{ currentResource.uploaderName }}</p>
            <p><strong>上传时间：</strong>{{ formatDate(currentResource.createTime) }}</p>
            <p><strong>浏览次数：</strong>{{ currentResource.viewCount }}</p>
            <p v-if="currentResource.type === 'DOCUMENT'"><strong>下载次数：</strong>{{ currentResource.downloadCount }}</p>
            <p v-if="currentResource.tags"><strong>标签：</strong>{{ currentResource.tags }}</p>
            
            <div v-if="currentResource.status !== 'PENDING'" class="review-info">
              <p><strong>审核者：</strong>{{ currentResource.reviewerName }}</p>
              <p><strong>审核时间：</strong>{{ formatDate(currentResource.reviewTime) }}</p>
              <p v-if="currentResource.reviewComment"><strong>审核意见：</strong>{{ currentResource.reviewComment }}</p>
            </div>
          </div>
        </div>
        
        <div class="detail-actions" v-if="currentResource.status === 'PENDING'">
          <el-button type="success" @click="reviewResource(currentResource, 'APPROVED')">
            <el-icon><Check /></el-icon>
            通过审核
          </el-button>
          <el-button type="danger" @click="reviewResource(currentResource, 'REJECTED')">
            <el-icon><Close /></el-icon>
            拒绝审核
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="reviewDialogVisible"
      :title="reviewAction === 'APPROVED' ? '通过审核' : '拒绝审核'"
      width="50%"
    >
      <el-form :model="reviewForm" ref="reviewFormRef" label-width="100px">
        <el-form-item label="审核意见" prop="comment">
          <el-input 
            v-model="reviewForm.comment" 
            type="textarea" 
            :rows="4"
            :placeholder="reviewAction === 'APPROVED' ? '请输入通过意见（可选）' : '请输入拒绝原因'"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReview" :loading="reviewing">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑资源对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑资源"
      width="60%"
      :before-close="handleCloseEdit"
    >
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="资源标题" prop="title">
          <el-input v-model="editForm.title" placeholder="请输入资源标题" />
        </el-form-item>
        
        <el-form-item label="资源分类" prop="category">
          <el-select v-model="editForm.category" placeholder="请选择资源分类" style="width: 100%">
            <el-option label="教学课件" value="TEACHING" />
            <el-option label="科研资料" value="SCIENTIFIC" />
            <el-option label="图书文献" value="LITERATURE" />
            <el-option label="共享设备" value="EQUIPMENT" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="资源类型" prop="type">
          <el-input v-model="editForm.type" :readonly="true" style="width: 100%" disabled />
        </el-form-item>
        
        <el-form-item label="资源描述" prop="description">
          <el-input 
            v-model="editForm.description" 
            type="textarea" 
            :rows="4"
            placeholder="请输入资源描述"
          />
        </el-form-item>
        
        <el-form-item label="标签" prop="tags">
          <el-input v-model="editForm.tags" placeholder="请输入标签，多个标签用逗号分隔" />
        </el-form-item>
        
        <el-form-item label="上传文件" prop="file" v-if="editForm.type === 'DOCUMENT'">
          <el-upload
            ref="editUploadRef"
            :auto-upload="false"
            :limit="1"
            :on-change="handleEditFileChange"
            :on-remove="handleEditFileRemove"
            accept=".pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.txt,.zip,.rar"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持PDF、Word、PPT、Excel、TXT、ZIP、RAR格式，文件大小不超过50MB
              </div>
            </template>
          </el-upload>
          <div v-if="editForm.fileName" class="current-file">
            <el-icon><Document /></el-icon>
            <span>当前文件：{{ editForm.fileName }}</span>
          </div>
        </el-form-item>
        
        <el-form-item label="设备信息" prop="equipmentInfo" v-if="editForm.type === 'EQUIPMENT'">
          <el-input 
            v-model="editForm.equipmentInfo" 
            type="textarea" 
            :rows="3"
            placeholder="请输入设备详细信息（JSON格式）"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit" :loading="editing">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设备预约管理对话框 -->
    <el-dialog
      v-model="bookingManageDialogVisible"
      title="设备预约管理"
      width="90%"
      :before-close="handleCloseBookingManage"
    >
      <div class="booking-manage-content">
        <!-- 筛选条件 -->
        <div class="booking-filter" style="margin-bottom: 20px;">
          <el-row :gutter="20">
            <el-col :span="4">
              <el-select v-model="bookingFilterStatus" placeholder="选择状态" style="width: 100%" @change="handleBookingSearch">
                <el-option label="全部状态" value="" />
                <el-option label="待审批" value="PENDING" />
                <el-option label="已通过" value="APPROVED" />
                <el-option label="已拒绝" value="REJECTED" />
                <el-option label="已取消" value="CANCELLED" />
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-input
                v-model="bookingSearchKeyword"
                placeholder="搜索设备名称或申请人"
                prefix-icon="Search"
                clearable
                @keyup.enter="handleBookingSearch"
              />
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="handleBookingSearch">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
            </el-col>
          </el-row>
        </div>
        
        <!-- 预约列表 -->
        <el-table :data="bookingList" v-loading="bookingLoading" style="width: 100%">
          <el-table-column prop="resourceTitle" label="设备名称" min-width="150" />
          <el-table-column prop="userName" label="申请人" width="120" />
          <el-table-column prop="bookingDate" label="预约日期" width="120">
            <template #default="scope">
              {{ formatDate(scope.row.bookingDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="startTime" label="开始时间" width="100" />
          <el-table-column prop="endTime" label="结束时间" width="100" />
          <el-table-column prop="purpose" label="使用目的" min-width="200" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getBookingStatusTagType(scope.row.status)">
                {{ getBookingStatusName(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="申请时间" width="150">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button 
                v-if="scope.row.status === 'PENDING'"
                type="success" 
                size="small" 
                @click="approveBooking(scope.row.id)"
              >
                通过
              </el-button>
              <el-button 
                v-if="scope.row.status === 'PENDING'"
                type="danger" 
                size="small" 
                @click="rejectBooking(scope.row.id)"
              >
                拒绝
              </el-button>
              <el-button 
                type="primary" 
                size="small" 
                @click="viewBookingDetail(scope.row)"
              >
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-section" style="margin-top: 20px;">
          <el-pagination
            v-model:current-page="bookingCurrentPage"
            v-model:page-size="bookingPageSize"
            :page-sizes="[10, 20, 50]"
            :total="bookingTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleBookingSizeChange"
            @current-change="handleBookingCurrentChange"
          />
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="bookingManageDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Clock, 
  Check, 
  Close,
  Document,
  Calendar
} from '@element-plus/icons-vue'
import { 
  getAllResources,
  getResourceById, 
  reviewResource as reviewResourceApi, 
  deleteResource as deleteResourceApi,
  updateResource as updateResourceApi,
  getPendingBookings,
  approveBooking as approveBookingApi,
  rejectBooking as rejectBookingApi
} from '@/api/resource'

export default {
  name: 'ResourceManagePage',
  components: {
    Search,
    Clock,
    Check,
    Close,
    Document,
    Calendar
  },
  setup() {
    // 筛选和搜索
    const filterCategory = ref('')
    const filterStatus = ref('')
    const searchKeyword = ref('')
    
    // 计算是否有活跃的筛选条件
    const hasActiveFilters = computed(() => {
      return (filterCategory.value && filterCategory.value.trim()) ||
             (filterStatus.value && filterStatus.value.trim()) ||
             (searchKeyword.value && searchKeyword.value.trim())
    })
    
    // 分页
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    
    // 数据
    const resourceList = ref([])
    const loading = ref(false)
    
    // 预约管理数据
    const bookingList = ref([])
    const bookingLoading = ref(false)
    const bookingCurrentPage = ref(1)
    const bookingPageSize = ref(10)
    const bookingTotal = ref(0)
    const bookingFilterStatus = ref('')
    const bookingSearchKeyword = ref('')
    
    // 对话框控制
    const detailVisible = ref(false)
    const reviewDialogVisible = ref(false)
    const bookingManageDialogVisible = ref(false)
    const currentResource = ref(null)
    const reviewAction = ref('')
    const reviewing = ref(false)
    
    // 审核表单
    const reviewFormRef = ref()
    const reviewForm = ref({
      comment: ''
    })
    
    // 编辑对话框
    const editDialogVisible = ref(false)
    const editForm = ref({
      title: '',
      category: '',
      type: '',
      description: '',
      tags: '',
      fileName: '',
      fileSize: 0,
      fileExtension: '',
      equipmentInfo: ''
    })
    const editRules = ref({
      title: [
        { required: true, message: '请输入资源标题', trigger: 'blur' },
        { max: 255, message: '资源标题长度不能超过255个字符', trigger: 'blur' }
      ],
      category: [
        { required: true, message: '请选择资源分类', trigger: 'change' }
      ],
      type: [
        { required: true, message: '请选择资源类型', trigger: 'change' }
      ],
      description: [
        { required: true, message: '请输入资源描述', trigger: 'blur' },
        { max: 1000, message: '资源描述长度不能超过1000个字符', trigger: 'blur' }
      ],
      tags: [
        { max: 255, message: '标签长度不能超过255个字符', trigger: 'blur' }
      ],
      equipmentInfo: [
        { max: 1000, message: '设备信息长度不能超过1000个字符', trigger: 'blur' }
      ]
    })
    const editFormRef = ref()
    const editUploadRef = ref()
    const editing = ref(false)
    
    // 分类变更时自动设置类型
    watch(() => editForm.value.category, (val) => {
      if (val === 'EQUIPMENT') {
        editForm.value.type = 'EQUIPMENT'
      } else {
        editForm.value.type = 'DOCUMENT'
      }
    }, { immediate: true })
    
    // 获取资源列表
    const fetchResourceList = async () => {
      loading.value = true
      try {
        const params = {
          current: currentPage.value,
          size: pageSize.value
        }
        
        // 只有当筛选条件不为空时才添加到参数中
        if (filterCategory.value && filterCategory.value.trim()) {
          params.category = filterCategory.value
        }
        
        if (filterStatus.value && filterStatus.value.trim()) {
          params.status = filterStatus.value
        }
        
        if (searchKeyword.value && searchKeyword.value.trim()) {
          params.keyword = searchKeyword.value
        }
        
        const response = await getAllResources(params)
        if (response.code === 200) {
          resourceList.value = response.data.records
          total.value = response.data.total
          
          // 调试输出：打印资源列表数据
          console.log('获取到的资源列表:', resourceList.value.map(item => ({
            id: item.id,
            resourceId: item.resourceId,
            title: item.title,
            status: item.status
          })))
        } else {
          ElMessage.error(response.message || '获取资源列表失败')
        }
      } catch (error) {
        console.error('获取资源列表失败:', error)
        ElMessage.error('获取资源列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 搜索
    const handleSearch = () => {
      currentPage.value = 1
      fetchResourceList()
    }
    
    // 清除所有筛选条件
    const clearFilters = () => {
      filterCategory.value = ''
      filterStatus.value = ''
      searchKeyword.value = ''
      currentPage.value = 1
      fetchResourceList()
    }
    
    // 显示待审核资源
    const showPendingResources = () => {
      filterStatus.value = 'PENDING'
      handleSearch()
    }
    
    // 分页处理
    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
      fetchResourceList()
    }
    
    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchResourceList()
    }
    
    // 查看资源详情
    const viewResourceDetail = async (resource) => {
      // 调试输出，确保 id/resourceId 一致
      console.log('查看资源详情:', {
        id: resource.id,
        resourceId: resource.resourceId,
        title: resource.title,
        status: resource.status
      })
      
      if (!resource.id) {
        ElMessage.error('资源主键id不存在，无法查看详情')
        return
      }
      
      try {
        console.log('请求资源详情，ID:', resource.id)
        const response = await getResourceById(resource.id)
        console.log('资源详情响应:', response)
        
        if (response.code === 200) {
          currentResource.value = response.data
          detailVisible.value = true
        } else {
          ElMessage.error(response.message || '获取资源详情失败')
        }
      } catch (error) {
        console.error('获取资源详情失败:', error)
        ElMessage.error('获取资源详情失败')
      }
    }
    
    // 审核资源
    const reviewResource = (resource, action) => {
      currentResource.value = resource
      reviewAction.value = action
      reviewForm.value.comment = ''
      reviewDialogVisible.value = true
    }
    
    // 提交审核
    const submitReview = async () => {
      if (reviewAction.value === 'REJECTED' && !reviewForm.value.comment.trim()) {
        ElMessage.error('拒绝审核时必须填写拒绝原因')
        return
      }
      
      reviewing.value = true
      try {
        const response = await reviewResourceApi(currentResource.value.id, {
          status: reviewAction.value,
          comment: reviewForm.value.comment
        })
        
        if (response.code === 200) {
          ElMessage.success('审核完成')
          reviewDialogVisible.value = false
          detailVisible.value = false
          fetchResourceList()
        } else {
          ElMessage.error(response.message || '审核失败')
        }
      } catch (error) {
        console.error('审核失败:', error)
        ElMessage.error('审核失败')
      } finally {
        reviewing.value = false
      }
    }
    
    // 删除资源
    const deleteResource = async (resource) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除资源"${resource.title}"吗？此操作不可恢复。`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const response = await deleteResourceApi(resource.id)
        if (response.code === 200) {
          ElMessage.success('删除成功')
          fetchResourceList()
        } else {
          ElMessage.error(response.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }
    
    // 关闭对话框
    const handleCloseDetail = () => {
      detailVisible.value = false
      currentResource.value = null
    }
    
    // 关闭编辑对话框
    const handleCloseEdit = () => {
      editDialogVisible.value = false
      currentResource.value = null
      editForm.value = {
        title: '',
        category: '',
        type: '',
        description: '',
        tags: '',
        fileName: '',
        fileSize: 0,
        fileExtension: '',
        equipmentInfo: ''
      }
    }
    
    // 编辑文件处理
    const handleEditFileChange = (file) => {
      editForm.value.file = file.raw
    }
    
    const handleEditFileRemove = () => {
      editForm.value.file = null
    }
    
    // 编辑资源
    const editResource = (resource) => {
      currentResource.value = resource
      editDialogVisible.value = true
      editForm.value = {
        title: resource.title,
        category: resource.category,
        type: resource.type,
        description: resource.description,
        tags: resource.tags,
        fileName: resource.fileName,
        fileSize: resource.fileSize,
        fileExtension: resource.fileExtension,
        equipmentInfo: resource.equipmentInfo
      }
    }
    
    // 提交编辑
    const submitEdit = async () => {
      editFormRef.value.validate(async (valid) => {
        if (valid) {
          editing.value = true
          try {
            const formData = new FormData()
            formData.append('id', currentResource.value.id)
            formData.append('title', editForm.value.title)
            formData.append('description', editForm.value.description)
            formData.append('category', editForm.value.category)
            formData.append('type', editForm.value.type)
            formData.append('tags', editForm.value.tags || '')
            
            if (editForm.value.type === 'DOCUMENT' && editForm.value.file) {
              formData.append('file', editForm.value.file)
            }
            
            if (editForm.value.type === 'EQUIPMENT') {
              formData.append('equipmentInfo', editForm.value.equipmentInfo || '')
            }
            
            const response = await updateResourceApi(formData)
            
            if (response.code === 200) {
              ElMessage.success('资源更新成功')
              editDialogVisible.value = false
              fetchResourceList()
            } else {
              ElMessage.error(response.message || '更新失败')
            }
          } catch (error) {
            console.error('更新失败:', error)
            ElMessage.error('更新失败')
          } finally {
            editing.value = false
          }
        }
      })
    }
    
    // 工具函数
    const getCategoryName = (category) => {
      const categoryMap = {
        'TEACHING': '教学课件',
        'SCIENTIFIC': '科研资料',
        'LITERATURE': '图书文献',
        'EQUIPMENT': '共享设备'
      }
      return categoryMap[category] || category
    }
    
    const getTypeName = (type) => {
      const typeMap = {
        'DOCUMENT': '文档',
        'EQUIPMENT': '设备'
      }
      return typeMap[type] || type
    }
    
    const getStatusName = (status) => {
      const statusMap = {
        'PENDING': '待审核',
        'APPROVED': '已通过',
        'REJECTED': '已拒绝'
      }
      return statusMap[status] || status
    }
    
    const getCategoryTagType = (category) => {
      const typeMap = {
        'TEACHING': 'primary',
        'SCIENTIFIC': 'success',
        'LITERATURE': 'warning',
        'EQUIPMENT': 'info'
      }
      return typeMap[category] || ''
    }
    
    const getTypeTagType = (type) => {
      return type === 'DOCUMENT' ? 'danger' : 'warning'
    }
    
    const getStatusTagType = (status) => {
      const typeMap = {
        'PENDING': 'warning',
        'APPROVED': 'success',
        'REJECTED': 'danger'
      }
      return typeMap[status] || ''
    }
    
    const formatFileSize = (bytes) => {
      if (!bytes) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }
    
    const formatDate = (dateStr) => {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return date.toLocaleString('zh-CN')
    }
    
    const getBookingStatusTagType = (status) => {
      const typeMap = {
        'PENDING': 'warning',
        'APPROVED': 'success',
        'REJECTED': 'danger',
        'CANCELLED': 'info'
      }
      return typeMap[status] || ''
    }
    
    const getBookingStatusName = (status) => {
      const statusMap = {
        'PENDING': '待审批',
        'APPROVED': '已通过',
        'REJECTED': '已拒绝',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || status
    }
    
    // 获取预约列表
    const fetchBookingList = async () => {
      bookingLoading.value = true
      try {
        const params = {
          current: bookingCurrentPage.value,
          size: bookingPageSize.value
        }
        
        if (bookingFilterStatus.value && bookingFilterStatus.value.trim()) {
          params.status = bookingFilterStatus.value
        }
        
        if (bookingSearchKeyword.value && bookingSearchKeyword.value.trim()) {
          params.keyword = bookingSearchKeyword.value
        }
        
        const response = await getPendingBookings(params)
        if (response.code === 200) {
          bookingList.value = response.data || []
          bookingTotal.value = response.total || 0
        } else {
          ElMessage.error(response.message || '获取预约列表失败')
        }
      } catch (error) {
        console.error('获取预约列表失败:', error)
        ElMessage.error('获取预约列表失败')
      } finally {
        bookingLoading.value = false
      }
    }
    
    // 预约搜索
    const handleBookingSearch = () => {
      bookingCurrentPage.value = 1
      fetchBookingList()
    }
    
    // 预约分页处理
    const handleBookingSizeChange = (val) => {
      bookingPageSize.value = val
      bookingCurrentPage.value = 1
      fetchBookingList()
    }
    
    const handleBookingCurrentChange = (val) => {
      bookingCurrentPage.value = val
      fetchBookingList()
    }
    
    // 通过预约
    const approveBooking = async (bookingId) => {
      try {
        await ElMessageBox.confirm('确定要通过这个预约申请吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await approveBookingApi(bookingId, {})
        if (response.code === 200) {
          ElMessage.success('预约申请已通过')
          fetchBookingList()
        } else {
          ElMessage.error(response.message || '操作失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('通过预约失败:', error)
          ElMessage.error('操作失败')
        }
      }
    }
    
    // 拒绝预约
    const rejectBooking = async (bookingId) => {
      try {
        const { value: comment } = await ElMessageBox.prompt('请输入拒绝原因', '拒绝预约', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputType: 'textarea',
          inputPlaceholder: '请输入拒绝原因'
        })
        
        const response = await rejectBookingApi(bookingId, { comment })
        if (response.code === 200) {
          ElMessage.success('预约申请已拒绝')
          fetchBookingList()
        } else {
          ElMessage.error(response.message || '操作失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('拒绝预约失败:', error)
          ElMessage.error('操作失败')
        }
      }
    }
    
    // 查看预约详情
    const viewBookingDetail = (booking) => {
      ElMessageBox.alert(`
        <div style="text-align: left;">
          <p><strong>设备名称：</strong>${booking.resourceTitle}</p>
          <p><strong>申请人：</strong>${booking.userName}</p>
          <p><strong>预约日期：</strong>${formatDate(booking.bookingDate)}</p>
          <p><strong>时间：</strong>${booking.startTime} - ${booking.endTime}</p>
          <p><strong>使用目的：</strong>${booking.purpose}</p>
          <p><strong>状态：</strong>${getBookingStatusName(booking.status)}</p>
          <p><strong>申请时间：</strong>${formatDate(booking.createTime)}</p>
          ${booking.approverName ? `<p><strong>审批人：</strong>${booking.approverName}</p>` : ''}
          ${booking.approveTime ? `<p><strong>审批时间：</strong>${formatDate(booking.approveTime)}</p>` : ''}
          ${booking.approveComment ? `<p><strong>审批意见：</strong>${booking.approveComment}</p>` : ''}
        </div>
      `, '预约详情', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定'
      })
    }
    
    // 打开预约管理对话框
    const openBookingManageDialog = () => {
      bookingManageDialogVisible.value = true
      bookingCurrentPage.value = 1
      bookingFilterStatus.value = ''
      bookingSearchKeyword.value = ''
      fetchBookingList()
    }
    
    // 关闭预约管理对话框
    const handleCloseBookingManage = () => {
      bookingManageDialogVisible.value = false
    }
    
    // 初始化
    onMounted(() => {
      fetchResourceList()
    })
    
    return {
      filterCategory,
      filterStatus,
      searchKeyword,
      hasActiveFilters,
      currentPage,
      pageSize,
      total,
      resourceList,
      loading,
      bookingList,
      bookingLoading,
      bookingCurrentPage,
      bookingPageSize,
      bookingTotal,
      bookingFilterStatus,
      bookingSearchKeyword,
      detailVisible,
      reviewDialogVisible,
      bookingManageDialogVisible,
      currentResource,
      reviewAction,
      reviewing,
      reviewFormRef,
      reviewForm,
      editDialogVisible,
      editForm,
      editRules,
      editFormRef,
      editUploadRef,
      editing,
      handleSearch,
      clearFilters,
      showPendingResources,
      handleSizeChange,
      handleCurrentChange,
      viewResourceDetail,
      reviewResource,
      submitReview,
      deleteResource,
      handleCloseDetail,
      handleCloseEdit,
      handleEditFileChange,
      handleEditFileRemove,
      editResource,
      submitEdit,
      getCategoryName,
      getTypeName,
      getStatusName,
      getCategoryTagType,
      getTypeTagType,
      getStatusTagType,
      formatFileSize,
      formatDate,
      getBookingStatusTagType,
      getBookingStatusName,
      handleBookingSearch,
      handleBookingSizeChange,
      handleBookingCurrentChange,
      approveBooking,
      rejectBooking,
      viewBookingDetail,
      openBookingManageDialog,
      handleCloseBookingManage
    }
  }
}
</script>

<style scoped>
.resource-manage-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
  text-align: center;
}

.page-header h2 {
  color: #303133;
  margin-bottom: 10px;
}

.page-header p {
  color: #606266;
  font-size: 14px;
}

.filter-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.filter-status {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.resource-table {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.resource-detail {
  padding: 20px 0;
}

.detail-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.detail-header h3 {
  color: #303133;
  margin-bottom: 10px;
}

.detail-meta {
  display: flex;
  gap: 8px;
}

.detail-content {
  margin-bottom: 20px;
}

.detail-content p {
  margin-bottom: 10px;
  line-height: 1.6;
}

.file-detail,
.equipment-detail {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin: 15px 0;
}

.equipment-detail pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.detail-info {
  background: #fafafa;
  padding: 15px;
  border-radius: 4px;
  margin: 15px 0;
}

.review-info {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.detail-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.current-file {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
  padding: 8px;
  background: #f5f7fa;
  border-radius: 4px;
}
</style> 